package org.asiainfo.common.mybatis.stream.reporter;

import cn.hutool.json.JSONUtil;
import com.mybatisflex.core.audit.AuditMessage;
import com.mybatisflex.core.audit.MessageReporter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.asiainfo.common.core.mq.Messaging;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.UUID;

/**
 * SQL审计 自定义MessageReporter
 *
 * @author dotor-ww
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class MybatisFlexMessageReporter implements MessageReporter {

    private final StreamBridge streamBridge;

    /**
     * 发送消息
     *
     * @param messages SQL 审计详细消息
     */
    @Override
    public void sendMessages(List<AuditMessage> messages) {
        for (AuditMessage auditMessage : messages) {
            log.debug("\n\u001B[31m" + "执行时间：{}ms \u001B[0m" + " \u001B[35m" + "语句: {} \u001B[0m",
                auditMessage.getElapsedTime(),
                auditMessage.getFullSql());
            sendMessage(auditMessage);
        }
    }

    /**
     * 发送消息到rabbitmq
     * @param auditMessage SQL 审计详细消息
     */
    private void sendMessage(AuditMessage auditMessage){
        Messaging messaging = new Messaging().setMsgId(UUID.randomUUID().toString()).setMsgText(JSONUtil.toJsonStr(auditMessage));
        streamBridge.send("log-out-0", MessageBuilder.withPayload(messaging).build());
    }
}
